const fse = require('fs-extra');
const { toPromise } = require('..');
const path = require('path');
const { log } = require('console');
const { v4 } = require('uuid');

const util = require('util');
const fs = require('fs');
const exec = util.promisify(require('child_process').exec);
const access = util.promisify(fs.access);


module.exports = {
    // 可读写的盘符
    async getFirstReadableWritableDrive() {
        try {
            const { stdout } = await exec('wmic logicaldisk get name');
            const drives = stdout.split('\n').filter(Boolean).slice(1).map(drive => drive.trim());  // 使用 trim 方法移除空白字符
            for (let drive of drives) {
                try {
                    await access(drive, fs.constants.R_OK | fs.constants.W_OK);
                    return drive; // 返回第一个可读写的盘符
                } catch (err) {
                    // 不做处理，直接尝试下一个盘符
                }
            }
            throw new Error("No readable and writable drives found."); // 如果所有盘符都不可读写，抛出错误
        } catch (error) {
            console.error(`Error getting drives: ${error}`);
        }
    },
    // 返回所有盘符
    async getAllDrives() {
        try {
            const { stdout } = await exec('wmic logicaldisk get name');
            const drives = stdout.split('\n').filter(Boolean).slice(1).map(drive => drive.trim());  // 使用 trim 方法移除空白字符
            return drives;
        } catch (error) {
            console.error(`Error getting drives: ${error}`);
        }
    },
    // 检查目录是否存在并有读写权限
    checkDirectoryExistenceAndAccess: async function (directoryPath) {
        // 查看目录是否存在
        const isFileExist = await fse.pathExists(directoryPath);
        if (isFileExist) {
            return fse.accessSync(directoryPath, fse.constants.R_OK | fse.constants.W_OK) === undefined;
        } else {
            // 如果目录不存在则创建目录
            await fse.mkdir(directoryPath);
            return true;
        }
    },
    // 查看文件是否存在
    checkFileExistence: async function (filePath) {
        return await fse.pathExists(filePath);
    },
    // 查看盘符是否允许读写
    checkDiskRWAccess: async function (diskPath) {
        return await fse.access(diskPath, fse.constants.R_OK | fse.constants.W_OK);
    },
    // 删除文件
    deleteFile: async function (filePath) {
        return await fse.remove(filePath);
    },
    // 删除文件夹
    deleteDirectory: async function (directoryPath) {
        return await fse.remove(directoryPath);
    },

    // 创建文件
    createFile: function (filePath) {
        return fse.writeFile(filePath, 'Hello, world!');
    },
    // 创建文件夹
    createDirectory: function (directoryPath) {
        return fse.mkdirSync(directoryPath);
    },

    // 读取文件内容
    readFile: function (filePath) {
        return fse.readFile(filePath, 'utf8');
    },

    // 生成文件树数据结构的函数
    generateFileTree: async function (dirPath) {
        const stats = await fse.stat(dirPath);
        if (!stats.isDirectory()) {
            return {
                name: path.basename(dirPath).split('.')[0],
                extname: path.extname(dirPath).replace('.', ''),
                path: dirPath.replace(/\\/g, '/'),
                type: 'file',
                children: []
            };
        }
        const children = await Promise.all((await fse.readdir(dirPath)).map(async (childName) => {
            return await this.generateFileTree(path.join(dirPath, childName));
        }));
        return { name: path.basename(dirPath), path: dirPath.replace(/\\/g,'/'), type: 'directory', children };
    },
    fetchVideoBuffer: function (filePath) {
        return new Promise(async (resolve, reject) => {
            try {
                const buffer = fse.readFileSync(filePath);
                resolve({ type: 'success', message: '视频文件Buffer数据读取成功！', buffer })
            } catch (error) {
                reject({ type: 'error', message: error.message })
            }
        })
    },

    getDirectoryInfo: async function (directoryPath) {
        try {
            const stats = await fse.stat(directoryPath);
            return stats;
        } catch (error) {
            console.error(`Error getting directory info: ${error}`);
        }
    }

}